package com.example.exampleretry.service;

import com.example.exampleretry.entity.Customer;
import com.example.exampleretry.repository.CustomerRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.RetryPolicy;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.atomic.AtomicInteger;

@RequiredArgsConstructor
@Slf4j
@Service
public class CustomerService {
    private final CustomerRepository customerRepository;
    private AtomicInteger counter = new AtomicInteger(0);

    @Retryable(recover = "recover", retryFor = RuntimeException.class, maxAttempts = 5, backoff = @Backoff(delay = 3000))
    public Mono<Customer> createCustomer(Customer customer) {
        log.info("start do something...");
        counter.incrementAndGet();
        if (counter.get() == 3) {
            return this.customerRepository.save(customer);
        }
        if (customer.getCustomerName().equals("hetonghai318")) {
            throw new RuntimeException("test example");
        }
        return this.customerRepository.save(customer);
    }


    public Flux<Customer> findAll() {
        return customerRepository.findAll();
    }

    @Recover
    public void recover(RuntimeException e) {
        log.info("start recover something...");
    }
}
